<script setup>
import CustomHeader from "components/CustomHeader.vue";
import {onMounted, reactive, watch} from "vue";
import {editUserInfo, getUserInfo, logout} from "service/user.js";
import {md5} from "js-md5";
import {Toast} from "vant";
import {removeLocal} from "utils/help.js";
const state = reactive({
  nicKNime: '',
  introduceSign: '',
  password: '',
  isChange: false
})
// 初始化方法
onMounted(async () => {
  // 接口获取个人信息
  const {data} = await getUserInfo()
  // 设置个人信息
  state.nicKNime = data.nicKNime
  state.introduceSign = data.introduceSign
  // 监听state的变化
  watch(state, () => {
    // 当数据变化时，将保存按钮恢复为可以单击状态
    state.isChange = true
  })
})
// 保存方法
const save = async () => {
  // 提交参数
  const params = {
    nicKNime: state.nicKNime,
    introduceSign: state.introduceSign
  }
  // 当密码出现的时候，添加密码到params 变量中
  if (state.password){
    // md5加密
    params.passwordMd5 = md5(params.passwordMd5)
  }
  await editUserInfo(params)
  Toast.success('保存成功')
}
// 登出方法
const handleLogout = async () => {
  // 调用登出接口
  const { resultCode } = await logout()
  if (resultCode === '200'){
    // 成功之后，清楚本地token信息
    removeLocal('token')
    // 返回首页 刷新
    window.location.href = '/'
  }
}
</script>

<template>
 <div class="seting-box">
<!--   自定义头部-->
   <custom-header :title="'账号管理'"></custom-header>
   <div class="input-item">
<!--     昵称输入框-->
     <van-field v-model="nicKNime" label="昵称"/>
<!--     个签输入框-->
     <van-field v-model="introduceSign" label="个性签名"/>
<!--     密码输入框-->
     <van-field v-model="password" type="password" label="修改密码"/>
   </div>
<!--   块级按钮 占满一行-->
   <van-button round class="save-btn" color="#1baeae" type="primary" @click="save" block>保存</van-button>
   <van-button round class="save-btn" color="#1baeae" type="primary" @click="handleLogout" block>退出登录</van-button>
 </div>
</template>

<style lang="less" scoped>
.seting-box{
  .save-btn{
    width: 80%;
    margin: 20px auto;

  }
}

</style>